package edu.hnu.cloudflight.android;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import edu.hnu.cloudflight.android.adapter.FlightNumberListAdapter;
import edu.hnu.cloudflight.android.domain.Flight;
import edu.hnu.cloudflight.android.domain.FlightRequest;
import edu.hnu.cloudflight.android.util.DateUtil;
import edu.hnu.cloudflight.android.util.HttpUtil;
import edu.hnu.cloudflight.android.util.StringUtil;

public class FlightCourseResultActivity extends Activity {

	private static final String TAG = "CopyOfFlightCourseResultActivity";

	private String start;
	private String end;
	private String startDate;
	@SuppressWarnings("unused")
	private String endDate;

	private CharSequence[] items;;

	private ProgressDialog pd;
	private Button preBtn;
	private Button nextBtn;
	private Button chooseCompany;
	private TextView todayIfo;
	private TextView starttoend;
	private ListView listView;
	private List<Flight> resultByCompany;

	private FlightNumberListAdapter adapter;
	private FlightCourseListTask task;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		if (bundle == null) {
			new AlertDialog.Builder(this).setTitle(R.string.flightnumberresult_diag_dataerror)
					.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(getApplicationContext(), FlightActivity.class);
							startActivity(intent);
						}
					}).show();
		}
		pd = new ProgressDialog(this);
		// pd.setTitle(R.string.flightnumberresult_diag_pleasewait);
		pd.setMessage(getResources().getString(R.string.flightnumberresult_diag_isloading));
		pd.setIndeterminate(true);
		pd.setCancelable(true);
		pd.show();
		start = bundle.getString("start");
		end = bundle.getString("end");
		startDate = bundle.getString("startDate");
		endDate = bundle.getString("endDate");

		setContentView(R.layout.fragment_flightcourseresult);
		listView = (ListView) findViewById(R.id.queryByFlightCourseList);
		preBtn = (Button) findViewById(R.id.btn_loadpreday);
		nextBtn = (Button) findViewById(R.id.btn_loadnextday);
		chooseCompany = (Button) findViewById(R.id.flightcourserresult_btn_id_choosecomapny);
		todayIfo = (TextView) findViewById(R.id.text_todayinfo);
		starttoend = (TextView) findViewById(R.id.text_starttoend);

		preBtn.setOnClickListener(new QueryOtherDateList(preBtn));

		nextBtn.setOnClickListener(new QueryOtherDateList(nextBtn));

		chooseCompany.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				new AlertDialog.Builder(FlightCourseResultActivity.this).setTitle(R.string.flightcourseresult_diag_choosecomapny)
						.setItems(items, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

								resultByCompany = new ArrayList<Flight>();
								String company = items[which].toString();
								chooseCompany.setText(StringUtil.getStringFromRes(R.string.flightcourseresult_text_choosecomapny) + company);
								if (company.equals("全部")) {
									resultByCompany = MyApplication.queryByFlightCourseResult;
								} else {
									for (Flight f : MyApplication.queryByFlightCourseResult) {
										if (company.equals(f.complany)) {
											resultByCompany.add(f);
										}
									}
								}
								adapter.setData(resultByCompany);
								adapter.notifyDataSetChanged();
							}
						}).show();
			}
		});

		// 解决Listview上下拖动时
		listView.setCacheColorHint(Color.TRANSPARENT);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(FlightCourseResultActivity.this, FlightNumberResultActivity.class);
				intent.setAction(FlightNumberResultActivity.ACTION_FROM_COURSERESULT);
				intent.putExtra("position", position);
				startActivity(intent);

			}
		});

		task = new FlightCourseListTask();
		task.execute("");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.flight, menu);
		return true;
	}

	public void showDate(TextView textView, Button preBtn, Button nextBtn, String today) {
		textView.setText(today);
		starttoend.setText(start + "到" + end);
		String preDate = DateUtil.getPreDateString(today);
		preBtn.setText(preDate);
		nextBtn.setText(DateUtil.getNextDateString(today));
	}

	public class QueryOtherDateList implements OnClickListener {

		private Button btn;

		public QueryOtherDateList(Button btn) {
			this.btn = btn;
		}

		@Override
		public void onClick(View v) {
			startDate = btn.getText().toString();
			if (task == null) {
				task = new FlightCourseListTask();
			}
			pd.show();
			task = new FlightCourseListTask();
			task.execute("");
		}

	}

	public class FlightCourseListTask extends AsyncTask<String, String, List<Flight>> {

		@Override
		protected List<Flight> doInBackground(String... paramss) {
			// StringBuilder sb = new StringBuilder();
			try {
				/*
				 * sb.append(MyApplication.queryByFlightCourseUrl).append("?start="
				 * ).append(URLEncoder.encode(start, "utf-8")).append("&end=")
				 * .append(URLEncoder.encode(end,
				 * "utf-8")).append("&date=").append
				 * (startDate).append("&key=").append(MyApplication.key);
				 * Log.i(TAG, sb.toString());
				 */
				Map<String, String> params = new HashMap<String, String>();
				params.put("start", start);
				params.put("end", end);
				params.put("date", startDate);
				params.put("key", MyApplication.key);
				String result = HttpUtil.getStringByGet(MyApplication.queryByFlightCourseUrl, params);
				// String result = HttpUtil.getStringByGet(sb.toString());
				Log.i(TAG, result);
				FlightRequest flightRequest = JSON.parseObject(result.substring(2), FlightRequest.class);
				if ("200".equals(flightRequest.resultcode)) {
					Log.i(TAG, String.valueOf(flightRequest.result.size()));
					MyApplication.queryByFlightCourseResult = flightRequest.result;
					return flightRequest.result;
				} else {
					Log.i("QueryResultError", flightRequest.resultcode + flightRequest.reason);
					return null;
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<Flight> result) {
			Log.i(TAG, "onPostExecute");
			if (pd != null) {
				pd.cancel();
			}
			Set<CharSequence> companySet = new LinkedHashSet<CharSequence>();
			companySet.add("全部");
			for (Flight f : result) {
				companySet.add(f.complany);
			}
			items = companySet.toArray(new CharSequence[] {});
			chooseCompany.setText(StringUtil.getStringFromRes(R.string.flightcourseresult_text_choosecomapny) + "全部");
			showDate(todayIfo, preBtn, nextBtn, startDate);
			adapter = new FlightNumberListAdapter(FlightCourseResultActivity.this, result, false);
			listView.setAdapter(adapter);
			// adapter.setData(result);
			adapter.notifyDataSetChanged();

		}

	}

}
